<?php


namespace App\Services\Admin\V1;


use App\Models\V1\Permission;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Collection;
use App\Http\Requests\Admin\V1\PermissionStoreRequest;
use App\Http\Requests\Admin\V1\PermissionUpdateRequest;

class PermissionService
{
    /**
     * @expalin GET ALL PERMISSIONS
     * @return Collection
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/4/1/10:25
     */
    public function all(): Collection
    {
        return Permission::get();
    }

    /**
     * @expalin GET PERMISSION BY ID
     * @param int $id
     * @return Permission
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/4/1/10:16
     */
    public function find(int $id): Permission
    {
        return Permission::findOrFail($id);
    }

    /**
     * @expalin CREATE PERMISSION
     * @param PermissionStoreRequest $request
     * @return Permission
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/4/1/10:18
     */
    public function store(PermissionStoreRequest $request): Permission
    {
        /** @var Permission $permission */
        $permission = Permission::create($request->only(['parent_id', 'name', 'title', 'is_enable']));

        return $permission;
    }

    /**
     * @expalin CREATE PERMISSION
     * @param int $id
     * @param PermissionUpdateRequest $request
     * @return Permission
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/4/1/10:35
     */
    public function update(int $id, PermissionUpdateRequest $request): Permission
    {
        $permission = $this->find($id);
        $permission->parent_id = (int) $request->input('parent_id');
        $permission->name = $request->input('name');
        $permission->title = $request->input('title');
        $permission->is_enable = $request->input('is_enable') ? Permission::ENABLE_TRUE : Permission::ENABLE_FALSE;
        $permission->save();

        return $permission;
    }

    /**
     * @expalin DELETE PERMISSION
     * @param int $id
     * @return bool
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/4/1/10:45
     */
    public function destroy(int $id): bool
    {
        DB::transaction(function () use ($id) {
            $permission = $this->find($id);

            // 删除关联角色
            $permission->roles()->detach();

            $permission->delete();
        });

        return true;
    }
}
